import type { IRequestOptions, IResponseData } from "./types";
import { useUserStore } from "../../store/modules/user";

// 读取 .env.xxx 文件的环境变量，作为请求前缀
const BASE_URL = import.meta.env.VITE_BASE_URL;

function request<T>({
  url,
  data = {},
  method = "GET",
}: IRequestOptions): Promise<T> {
  return new Promise((resolve, reject) => {
    const userStore = useUserStore();

    uni.request({
      url: BASE_URL + url,
      data,
      method,
      header: {
        token: userStore.token,
      },
      success(res) {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          // 请求成功
          const data = res.data as IResponseData<T>;

          if (data.code === 200) {
            // 功能成功
            resolve(data.data);
          } else {
            // 功能失败
            uni.showToast({
              title: "请求失败~",
              icon: "error",
            });
            reject();
          }
        } else {
          // 请求失败
          uni.showToast({
            title: "请求失败~",
            icon: "error",
          });
          reject();
        }
      },
      fail() {
        uni.showToast({
          title: "请求失败~",
          icon: "error",
        });
        reject();
      },
    });
  });
}

export default request;
